package com.chalk.rabbitmq;

import com.rabbitmq.client.Channel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Service;

import java.io.IOException;

/**
 * @author xiaoqiang
 * @Description
 * @date 2019/7/16 16:26
 */
@Service
public class MqReceiver {
    private static Logger log = LoggerFactory.getLogger(MqReceiver.class);

    /**
     * Direct模式
     * @param message
     */
    @RabbitListener(queues = RabbitMqConfig.QUEUE_A)
    public void receive(String message, Message mes, Channel channel){
        log.info("receive direct message = {}", message);
        try {
            // 手动确认消息
            channel.basicAck(mes.getMessageProperties().getDeliveryTag(),true);
            log.info("手动确[direct.queue.A]认消息");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @RabbitListener(queues= RabbitMqConfig.TOPIC_QUEUE1)
    public void receiveTopic1(String message, Message mes, Channel channel) {
        log.info(" topic  queue1 message:{}", message);
        try {
            // 手动确认消息
            channel.basicAck(mes.getMessageProperties().getDeliveryTag(),false);
            log.info("手动确认[topic.queue1]消息");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @RabbitListener(queues= RabbitMqConfig.TOPIC_QUEUE2)
    public void receiveTopic2(String message, Message mes, Channel channel) {
        log.info(" topic  queue2 message:{}", message);
        try {
            // 手动确认消息
            channel.basicAck(mes.getMessageProperties().getDeliveryTag(),true);
            log.info("手动确认[topic.queue2]消息");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @RabbitListener(queues= RabbitMqConfig.HEADER_QUEUE)
    public void receiveHeaderQueue(byte[] message, Message mes, Channel channel) {
        log.info(" header  queue message:{}", new String(message));
        try {
            // 手动确认消息
            channel.basicAck(mes.getMessageProperties().getDeliveryTag(),true);
            log.info("手动确认[header.queue]消息");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
